package util;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;

public class ConnectionData {
	public Socket socket;
	public ObjectOutputStream out;
	public ObjectInputStream in;
	public ArrayList<Object> recieved = new ArrayList<Object>();
	
	public ConnectionData(Socket socket){
		this.socket = socket;
		try{
			out = new ObjectOutputStream(socket.getOutputStream());
			in = new ObjectInputStream(socket.getInputStream());
			Thread recieve = new Thread(){
				public void run(){
					while(true){
						try{
							recieved.add(in.readObject());
						}catch (Exception e){}
					}
				}
			};
			recieve.start();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public boolean isClosed(){
		return socket.isClosed();
	}
	public void write(Object o) throws IOException{
		out.writeObject(o);
		out.flush();
	}
	
	public Object read(){
		if(recieved.size() > 0){
			Object temp = recieved.get(0);
			recieved.remove(0);
			return temp;
		}else{
			return null;
		}
	}
	
	public boolean connected(){
		return out != null && in != null && socket != null;
	}
	
	public void close(){
		try{
			in.close();
			out.flush();
			socket.close();
		}catch (Exception e){}
	}

}
